using System;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
using LP;

public enum ELogColor
{
    white,
    bule,
    red,
    yellow,
    black,
    green,
}

public class LogUtil : Singleton<LogUtil>, ILifecycle, IUpdate, ICanUpdate
{
    public bool IsUpdate { get; set; } = true;

    public void OnInit()
    {
        Application.logMessageReceivedThreaded += HandlerLog;
    }

    public void OnDestroy()
    {
        Application.logMessageReceivedThreaded -= HandlerLog;
    }

    private void HandlerLog(string logStr, string stackTrace, LogType type)
    {
#if UNITY_ANDROID || UNITY_IOS
        if (type == LogType.Log || type == LogType.Error)
        {
            WriteLogFile(logStr, stackTrace);
        }
#endif

    }
    public void Log(object str)
    {
        Debug.Log(str);
    }

    public void Warning(object str)
    {
        Debug.LogWarning(str);
    }

    public void Error(object str)
    {
        Debug.LogError(str);
    }

    public string GetColorString(string str, ELogColor logColor = ELogColor.bule)
    {
        return $"<color={Enum.GetName(typeof(ELogColor), logColor)}>{str}</color>";
    }

    private Queue<string> logContentToFileQueue = new Queue<string>();

#if UNITY_EDITOR
    private static string logDirectoryPath = $"{Application.dataPath}/LogFile";
#else
    private static string logDirectoryPath = $"{Application.persistentDataPath}/LogFile";
#endif

    private string filePath = $"{logDirectoryPath}/LogFile.txt";

    private void WriteLogFile(string logStr, string stackTrace)
    {
        if (!Directory.Exists(logDirectoryPath))
        {
            Directory.CreateDirectory(logDirectoryPath);
        }
        if (!File.Exists(filePath))
        {
            using (File.CreateText(filePath))
            {

            }
        }
        logContentToFileQueue.Enqueue($"{logStr}\nStackTrace:\n{stackTrace}RecordTime is {DateTime.Now.ToString()}\n");
    }

    public void OnUpdate(float delta)
    {
        if (logContentToFileQueue.Count > 0)
        {
            if (File.Exists(filePath))
            {
                using (var Writer = File.AppendText(filePath))
                {
                    Writer.Write(logContentToFileQueue.Dequeue());
                }
            }
        }
    }

    public void OnInitFinish()
    {
    }
}
